from flask import Blueprint,request
from app.utils.sqliteFunc import Sqlite
from app.utils.responseFunc import returnMsg


homebp = Blueprint("home",__name__)
sqlite = Sqlite()


@homebp.route("/about/me",methods=["get"])
def aboutMe():
    sql = "select nickName,email,about from tb_about;"
    data = sqlite.query(sql)
    return returnMsg(data=data)


@homebp.route("/banner/list")
def banner():
    """
    获取首页的轮播图的接口
    """
    sql = "select * from tb_banner where status = 1;"
    data = sqlite.query(sql)
    return returnMsg(data=data)


@homebp.route("/category/list")
def category():
    """
    获取博客的分类
    """
    sql = "select * from tb_category where status = 1;"
    data = sqlite.query(sql)
    return returnMsg(data=data)


@homebp.route("/article/list",methods=["post"])
def article():
    """
    获取文章列表
    """
    body = request.get_json()
    categoryId = body.get("categoryId")
    sql = "select a.id,a.title,a.createTime,b.category from tb_article a join tb_category b on a.categoryId = b.id where a.status = 1"
    if categoryId not in ("",None):
        sql = sql + " and a.categoryId = {}".format(categoryId)
    sql = sql + " limit 0,10;"
    data = sqlite.query(sql)
    return returnMsg(data=data)


@homebp.route("/article/info/<int:articleId>")
def article_info(articleId):
    """
    获取文章详情
    """
    sql = "select a.id,a.title,a.createTime,b.category,a.content from tb_article a join tb_category b on a.categoryId = b.id where a.status = 1 and a.id = {};".format(articleId)
    data = sqlite.query(sql)
    return returnMsg(data=data)



@homebp.route("/article/comment/list/<int:articleId>",methods=["get"])
def article_comment_list(articleId):
    """
    文章评论列表
    """
    sql = "select a.* from tb_article_comment a join tb_article b on a.articleId = b.id where a.status = 1 and a.articleId = {};".format(articleId)
    data = sqlite.query(sql)
    return returnMsg(data=data)


@homebp.route("/article/comment/save",methods=["post"])
def article_comment_save():
    """
    评论文章
    """
    body = request.get_json()
    email = body.get("email")
    content = body.get("content")
    articleId = body.get("articleId")
    sql = "insert into tb_article_comment (articleId,email,content) values ({},'{}','{}');".format(articleId,email,content)
    sqlite.commit(sql)
    return returnMsg()


@homebp.route("/login",methods=["post"])
def login():
    """
    登录
    """
    body = request.get_json()
    username = body.get("username")
    password = body.get("password")
    sql = "select * from tb_about where username = '{}';".format(username)
    data = sqlite.query(sql)
    if len(data) == 0:
        return returnMsg(code=0,msg="账号不存在")
    if data[0].get("password") != password:
        return returnMsg(code=0,msg="密码错误")
    token = "sadjhsdfsdd76347239483jxdhfjdsfertr8348"
    data[0].update(token=token)
    return returnMsg(data=data)


